﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Reflection;

namespace ObjectEditor.UserControls
{
    /// <summary>
    /// Interaction logic for PropertyEditorMultiObject.xaml
    /// </summary>
    public partial class PropertyEditorMultiObject : UserControl
    {
        public PropertyEditorMultiObject(PropertyEditorMultiObjectViewModel vm)
        {
            InitializeComponent();
            DataContext = vm;
            this.Unloaded += (x, y) =>
            {
                vm.Dispose();
            };
        }

        private void SelectedObjectPropertyGrid_SelectedObjectChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (e.NewValue == null) return;

            if (e.OldValue != null)
            {
                if (e.NewValue.GetType() == e.OldValue.GetType())
                {
                    return;
                }
            }

            var properties = new List<string>();
            var defs = SelectedObjectPropertyGrid.PropertyDefinitions = new Xceed.Wpf.Toolkit.PropertyGrid.PropertyDefinitionCollection();

            var pinfos = e.NewValue.GetType().GetProperties();
            foreach (var info in pinfos)
            {
                var attr = (System.ComponentModel.BrowsableAttribute)(info.GetCustomAttribute(typeof(System.ComponentModel.BrowsableAttribute), false));

                if (attr != null && attr.Browsable == false)
                {
                    continue;
                }
                else
                {
                    properties.Add(info.Name);
                }
            }

            foreach (var p in properties)
            {
                defs.Add(new Xceed.Wpf.Toolkit.PropertyGrid.PropertyDefinition()
                {
                    Name = p
                });
            }
        }
    }
}
